<template>
  <div class="teacher-courses">
    <!-- 搜索区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="教学安排ID">
            <el-input v-model="filterForm.teachId" placeholder="请输入教学安排ID" @keyup.enter="queryCourseDetail" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="queryCourseDetail">查询</el-button>
            <el-button type="default" @click="resetFilter">重置</el-button>
            <!-- 新增按钮 -->
            <el-button type="success" @click="addTeachesDialogVisible = true">新增教学安排</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增教学安排对话框 -->
    <el-dialog v-model="addTeachesDialogVisible" title="新增教学安排" width="50%">
      <el-form :model="addTeachesForm" label-width="150px">
        <el-form-item label="课程ID">
          <el-input v-model="addTeachesForm.courseId" placeholder="请输入课程ID"></el-input>
        </el-form-item>
        <el-form-item label="班级ID列表（逗号分隔）">
          <el-input v-model="addTeachesForm.classIds" placeholder="请输入班级ID列表（逗号分隔）"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addTeachesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addTeaches">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="queryDialogVisible" title="课程信息查询结果" width="50%" @close="handleQueryDialogClose">
      <el-form :model="queryCourseInfo" label-width="150px">
        <el-form-item label="教学安排ID">
          <el-input v-model="queryCourseInfo.teachId" disabled></el-input>
        </el-form-item>
        <el-form-item label="教授的学生班级id">
          <el-input v-model="queryCourseInfo.classIds" disabled></el-input>
        </el-form-item>
        <el-form-item label="教授的学生班级名称">
          <el-input v-model="queryCourseInfo.classNames" disabled></el-input>
        </el-form-item>
        <el-form-item label="教授的课程id">
          <el-input v-model="queryCourseInfo.courseId" disabled></el-input>
        </el-form-item>
        <el-form-item label="教授课程的老师id">
          <el-input v-model="queryCourseInfo.teacherId" disabled></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 课程列表 -->
    <el-card class="course-list-card">
      <div class="table-container">
        <el-table :data="courseList" stripe border @row-click="handleCourseClick" style="width: 100%;" max-height="500px">
          <el-table-column prop="teachId" label="教学ID"></el-table-column>
          <el-table-column prop="teacherId" label="教师ID"></el-table-column>
          <el-table-column prop="courseId" label="课程ID"></el-table-column>
          <el-table-column prop="courseName" label="课程名称"></el-table-column>
          <el-table-column prop="classIds" label="班级ID"></el-table-column>
          <el-table-column prop="classNames" label="班级名称"></el-table-column>
          <el-table-column prop="courseCredits" label="课程学分"></el-table-column>
          <el-table-column prop="courseDescription" label="课程描述"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="gotoAssignments(scope.row)">作业管理</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import {useRouter} from "vue-router";
const router = useRouter();
// 筛选条件
const filterForm = reactive({
  teachId: '',
});

// 表格数据和分页
const courseList = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 查询对话框相关
const queryDialogVisible = ref(false);
const queryCourseInfo = ref({
  teachId: '',
  classIds: '',
  classNames: '',
  courseId: '',
  teacherId: '',
});

// 新增教学安排对话框相关
const addTeachesDialogVisible = ref(false);
const addTeachesForm = ref({
  courseId: '',
  classIds: ''
});

// 查询课程详情
const queryCourseDetail = async () => {
  const teachId = filterForm.teachId;
  if (!teachId) {
    ElMessage.warning('请输入教学安排ID');
    return;
  }
  try {
    const response = await axios.get(`/teaches/getTeachesDetail?teachId=${teachId}`);
    if (response.data.flag) {
      queryCourseInfo.value = response.data.result;
      queryDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.reason || '查询失败');
    }
  } catch (error) {
    console.error('查询出错:', error);
    ElMessage.error('查询时发生错误，请稍后重试');
  }
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.teachId = '';
  fetchCourses();
};

// 获取课程列表
const fetchCourses = async () => {
  try {
    const formData =  new FormData();
    formData.append("page",currentPage.value);
    formData.append("size",pageSize.value);
    formData.append("teacherId",localStorage.getItem("teacherId"));
    const response = await axios.post('/teaches/getCourseTeachesInfoByTeacherId', formData);
    if (response.data.flag) {
      courseList.value = response.data.result || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response?.data.message || '获取课程列表失败');
    }
  } catch (error) {
    console.error('获取课程列表失败', error);
    ElMessage.error('获取课程列表失败，请稍后重试');
  }
};

// 分页控制
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchCourses();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchCourses();
};

// 跳转到作业管理页面
const gotoAssignments = (row) => {
  console.log(row)
  router.push({
    name: 'HomeworkManagement',
    query: row.teachId 
  });
};

// 处理查询对话框关闭
const handleQueryDialogClose = () => {
  queryDialogVisible.value = false;
  queryCourseInfo.value = {
    teachId: '',
    classIds: '',
    classNames: '',
    courseId: '',
    teacherId: '',
  };
};

// 新增教学安排
const addTeaches = async () => {
  try {
    const formData =  new FormData();
    formData.append("teacherId", localStorage.getItem("teacherId"));
    formData.append("classIds",addTeachesForm.value.classIds);
    formData.append("courseId",addTeachesForm.value.courseId);

    const response = await axios.post('/teaches/addTeaches', formData);
    if (response.data.flag) {
      ElMessage.success('新增教学安排成功');
      addTeachesDialogVisible.value = false;
      fetchCourses(); // 新增成功后刷新列表
    } else {
      ElMessage.error(response.data.reason || '新增教学安排失败');
    }
  } catch (error) {
    console.error('新增教学安排出错:', error);
    ElMessage.error('新增教学安排时发生错误，请稍后重试');
  }
};

onMounted(() => {
  fetchCourses();
});
</script>

<style scoped>
.teacher-courses {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.course-list-card {
  height: auto;
}

.table-container {
  height: 500px;
  overflow-y: auto;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>